﻿
using com.citizen.sdk.LabelPrint;
using LinqToExcel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Windows.Forms;
using Win.CSkin.Test.ISHIDA;

namespace Win.CSkin.Test
{
    public partial class Form1 : Form
    {
        List<KeyValuePair<string, string>> TestListPair = new List<KeyValuePair<string, string>>();
        List<string> TestListString = new List<string>();
        NAudioRecorder nar = new NAudioRecorder();

        public Form1()
        {
            InitializeComponent();
            this.richTextBox1.Text = Thread.CurrentThread.ManagedThreadId.ToString() + Environment.NewLine;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.richTextBox1.Text += "button1:" + Thread.CurrentThread.ManagedThreadId.ToString() + Environment.NewLine;

            //启动新线程执行BeginInvoke
            Thread thread = new Thread(new ThreadStart(UpdateText))
            {
                IsBackground = true
            };
            thread.Start();

            ////直接执行BeginInvoke
            //this.BeginInvoke((Action)(() =>
            //{
            //    this.richTextBox1.Text += "BeginInvoke:" + Thread.CurrentThread.ManagedThreadId.ToString() + Environment.NewLine;
            //}));
            //Thread.Sleep(3000);
        }

        private void UpdateText()
        {
            this.BeginInvoke((Action)(() =>
            {
                this.richTextBox1.Text += "UpdateText:" + Thread.CurrentThread.ManagedThreadId.ToString() + Environment.NewLine;
            }));
            try
            {
                this.BeginInvoke((Action)(() =>
                            {
                                this.richTextBox1.Text += "BeginInvoke:" + Thread.CurrentThread.ManagedThreadId.ToString() + Environment.NewLine;

                                try
                                {
                                    //测试报错获取
                                    throw new Exception("test");
                                }
                                catch (Exception ex) //BeginInvoke内部用trycatch可以获取报错信息
                                {
                                    richTextBox1.Text += ex.Message;
                                }

                            }));
                Thread.Sleep(3000);
            }
            catch (Exception ex)  //无法获取BeginInvoke内部的报错信息
            {
                MessageBox.Show(ex.Message);
            }
        }

        private readonly int Max_Item_Count = 10000;
        private void button2_Click(object sender, EventArgs e)
        {
            listView1.Items.Clear();
            new Thread((ThreadStart)(delegate ()
            {
                for (int i = 0; i < Max_Item_Count; i++)
                {
                    // 此处警惕值类型装箱造成的"性能陷阱"
                    listView1.Invoke((MethodInvoker)delegate ()
                    {
                        listView1.Items.Add(new ListViewItem(new string[]
                        { i.ToString(), string.Format("This is No.{0} item", i.ToString()) }));
                    });
                };
            }))
            .Start();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            dbListView1.Items.Clear();
            new Thread(delegate ()
            {
                for (int i = 0; i < Max_Item_Count; i++)
                {
                    // 此处警惕值类型装箱造成的"性能陷阱"
                    dbListView1.Invoke((MethodInvoker)delegate ()
                    {
                        dbListView1.Items.Add(new ListViewItem(new string[]
                        { i.ToString(), string.Format("This is No.{0} item", i.ToString()) }));
                    });
                };
            })
            .Start();
        }

        private void button4_Click(object sender, EventArgs e)
        {
            this.Close();
            //this.DialogResult = System.Windows.Forms.DialogResult.OK;
        }

        private void button5_Click(object sender, EventArgs e)
        {
            ////S模块
            //Int64 codeS = 0;
            //var list = ErrorCommon.GetPLCErrorInfoByCode(Convert.ToInt64(1000 + codeS));//S+Code

            ////A模块
            //Int64 codeA = 1024;  //D3000.10 A1024
            //list = ErrorCommon.GetPLCErrorInfoByCode(Convert.ToInt64(2000 + codeA));//A+Code

            ////B模块
            //Int64 codeB = 4398046511104;  //D3052.10 B4398046511104
            //list = ErrorCommon.GetPLCErrorInfoByCode(Convert.ToInt64(3000 + codeB));//B+Code

            ////C模块
            //Int64 codeC = 1024;   //D3100.10 C1024
            //list = ErrorCommon.GetPLCErrorInfoByCode(Convert.ToInt64(4000 + codeC));//C+Code

            ////D模块
            //Int64 codeD = 256;     //D3150.08 D256
            //list = ErrorCommon.GetPLCErrorInfoByCode(Convert.ToInt64(5000 + codeD));//D+Code

        }

        private void button6_Click(object sender, EventArgs e)
        {
            TestAttributeModel model = new TestAttributeModel();
            model.test1 = true;
            var listS = Utils.ForeachClassProperties(model);
        }

        private void button7_Click(object sender, EventArgs e)
        {
            NumberFormatInfo nfi = new CultureInfo("zh-cn", false).NumberFormat;
            var de = Convert.ToDecimal("55.00", nfi);

            var num = Math.Ceiling(1234 / 1000d);
            num = Math.Floor(1234 / 1000d);

            double dosage = 40;  //100
            double sup = 30;

            double drugAmt = dosage / sup;
            var ff = Convert.ToSingle(drugAmt);

            string amt = drugAmt.ToString().Trim();

            float DrugAMT = float.Parse(drugAmt.ToString("N3").Trim());


            short depth = 20;
            depth = (short)(depth >> 16);

        }

        private void button8_Click(object sender, EventArgs e)
        {
            TimeSpan timeSpan = TimeSpan.Zero;
            var ss = timeSpan.TotalSeconds;
            var ms = timeSpan.TotalMilliseconds;

            var begin = DateTime.Now.Ticks;
            var beginStr = DateTime.Now.ToString("yyyyMMddHHmmssfff");
            Thread.Sleep(2000);
            var end = DateTime.Now.Ticks;
            var endStr = DateTime.Now.ToString("yyyyMMddHHmmssfff");

            timeSpan = new TimeSpan(end - begin);
            var ms2 = timeSpan.TotalMilliseconds;
            var ss2 = timeSpan.TotalSeconds;
        }

        private void btnSQLite_Click(object sender, EventArgs e)
        {
            ICustomerRepository rep = new SqLiteCustomerRepository();
            var customer = new Customer
            {
                FirstName = "张",
                LastName = "机甲",
                DateOfBirth = DateTime.Now
            };
            rep.SaveCustomer(customer);

            Customer retrievedCustomer = rep.GetCustomer(customer.Id);

            JavaScriptSerializer jss = new JavaScriptSerializer();
            var json = jss.Serialize(retrievedCustomer);
            richTextBox1.Text = json;
        }

        /// <summary>
        /// PLC心跳发送
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button9_Click(object sender, EventArgs e)
        {
            richTextBox1.Text = string.Empty;
            int execCount = 0;

            int LiveCount = 1;
            short LiveFlag = 0;

            Stopwatch sw = new Stopwatch();
            Stopwatch swTimes = new Stopwatch();
            sw.Start();
            TimeSpan timeSpan = TimeSpan.Zero;
            var begin = DateTime.Now.Ticks;

            while (true)
            {
                if (LiveCount == 1)
                {
                    begin = DateTime.Now.Ticks;
                    swTimes.Restart();
                }

                //3秒（60*50=2000ms）写入一次信号，1、0交替写入
                if (LiveCount > 60)
                {
                    LiveCount = 0;
                    var arr = (short)(LiveFlag % 2); //发送信号
                    LiveFlag += 1;

                    var end = DateTime.Now.Ticks;
                    timeSpan = new TimeSpan(end - begin);
                    var ss2 = timeSpan.TotalSeconds;

                    swTimes.Stop();

                    //this.BeginInvoke((Action)(() =>
                    //{
                    richTextBox1.Text += ss2.ToString() + "|" + swTimes.ElapsedMilliseconds.ToString() + "--";
                    //}));

                    execCount++;
                    if (execCount == 5)
                    {
                        sw.Stop();
                        long times = sw.ElapsedMilliseconds;
                        richTextBox1.Text += (times / 1000).ToString();
                        break;
                    }
                }

                LiveCount += 1;
                Thread.Sleep(50);
            }
        }

        private void button10_Click(object sender, EventArgs e)
        {
            string sd = "20191016";
            var dt = DateTime.ParseExact(sd, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);

            var st = dt.ToString("yyyy-MM-dd");
        }

        private void button11_Click(object sender, EventArgs e)
        {
            string no = "612619,22538366,2019-10-15,01";

            var ss = no.PadRight(40, ' ');
            var len = ss.Length;

            var i = 1;
            var istr = i.ToString("D2");
        }

        private void btn_ISHIDA_Click(object sender, EventArgs e)
        {
            try
            {
                var Printer = new Printer_ISHIDA("ISHIDA L-1000-12", printPort.Text.Trim(), "3");
                long ErrCode = Printer.GetLabelPrinterState(out int pages, out string errState, out string ErrInfo);
                richTextBox1.Text = errState + " " + ErrInfo;

            }
            catch (Exception ex)
            {
                richTextBox1.Text = ex.Message;
            }

        }

        private void cP_DPS_Btn1_Click(object sender, EventArgs e)
        {
            PrinterAlarmEvent = PrinterAlarmShow;
            PrinterAlarmEvent?.Invoke(null);
        }
        private Action<Customer> PrinterAlarmEvent = null;
        private void PrinterAlarmShow(Customer model)
        {
            if (model == null) //无报警信息
            {
                return;
            }

        }

        private void cP_DPS_Btn2_Click(object sender, EventArgs e)
        {
            TextKeybord frm = new TextKeybord();
            frm.Show(this);
        }

        private void btn_CITIZEN_Click(object sender, EventArgs e)
        {
            LabelPrinter printer = new LabelPrinter();
            //连接打印机
            var connRes = printer.Connect(3, printPort.Text.Trim());
            //获取状态
            var res = printer.PrinterCheck();

        }

        private void btnSound_Click(object sender, EventArgs e)
        {
            FrmSoundTest frm = new FrmSoundTest();
            frm.Show(this);
        }

        private void btnDGV1_Click(object sender, EventArgs e)
        {
            FrmDGVTest1 frm = new FrmDGVTest1();
            frm.Show(this);
        }

        private void btnLstCollapse_Click(object sender, EventArgs e)
        {
            ListViewExtTest frm = new ListViewExtTest();
            frm.Show(this);
        }

        private void btnCboEx_Click(object sender, EventArgs e)
        {
            FrmComboTest frm = new FrmComboTest();
            frm.Show(this);
        }

        private void btnColorTrans_Click(object sender, EventArgs e)
        {
            string c = richTextBox1.Text.Trim();
            if (c.Length == 0)
            {
                c = "#FF0000";
            }
            //把十六进制颜色转化为color对象
            var color = ColorTranslator.FromHtml(c);
            //color = ColorTranslator.FromHtml("Red");
            btnColorTrans.BackColor = color;

            //把color对象转化为十六进制颜色
            var colorHex = ColorTranslator.ToHtml(Color.FromArgb(255, 255, 255));
            colorHex = ColorTranslator.ToHtml(Color.Red);
            btnColorTrans.ForeColor = ColorTranslator.FromHtml(colorHex);
        }

        private void ipixButton1_Click(object sender, EventArgs e)
        {
            //绑定数据源
            DataTable dt = new DataTable();
            DataColumn dc1 = new DataColumn("weibo", typeof(System.String));
            dt.Columns.Add(dc1);

            DataColumn dc2 = new DataColumn("mail", typeof(System.String));
            dt.Columns.Add(dc2);

            DataColumn dc3 = new DataColumn("blog", typeof(System.String));
            dt.Columns.Add(dc3);

            for (int i = 0; i < 50; i++)
            {
                DataRow dr = dt.NewRow();
                dr[0] = "下里巴人simple";
                dr[1] = "524300045@qq.com";
                dr[2] = "msdn" + i.ToString();
                dt.Rows.Add(dr);
            }
            uc_ChkList.DataSource = dt;
            uc_ChkList.DisplayMember = "weibo";
            uc_ChkList.ValueMember = "mail";
        }

        private void ipixButton2_Click(object sender, EventArgs e)
        {
            //添加项
            uc_ChkList.AddItems("邮箱:524300045@qq.com");
            uc_ChkList.AddItems("微博:下里巴人simple");
        }
        /// <summary>
        /// 获取选中项的文本
        /// </summary>
        private void uc_ChkList_ItemClick(object sender, ItemCheckEventArgs e)
        {
            string text = uc_ChkList.GetItemText(uc_ChkList.Items[e.Index]);
            MessageBox.Show(text);
        }

        private void btnReadIni_Click(object sender, EventArgs e)
        {
            var path = Application.StartupPath + "\\" + "Config.ini";
            IniHelper ini = new IniHelper(path);

            var str = ini.readString("sectionName", "KeyName");
            richTextBox1.Text = str;
        }

        private void btnWriteIni_Click(object sender, EventArgs e)
        {
            var str = richTextBox1.Text;

            var path = Application.StartupPath + "\\" + "Config.ini";
            IniHelper ini = new IniHelper(path);

            ini.writeString("sectionName", "KeyName", str);
        }

        /// <summary>
        /// 获取文件列表，删除重复文件
        /// </summary>
        private void btnGetFiles_Click(object sender, EventArgs e)
        {
            string path = "G:\\";
            getDirectory(path);

            TestListPair.ForEach(f =>
            {
                var fileName = f.Key;
                var fileFullName = f.Value;
                var arr = fileName.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                if (arr.Length <= 1) return;
                var name = arr[1]; //格式：001 听妈妈讲那过去的事情.wav
                TestListString.Add(name);
            });

            //查询重复文件（文件数量大于1）
            var repeat = TestListString
                 .GroupBy(x => x)
                 .Select(group => new
                 {
                     name = group.Key,
                     num = group.Count()
                 }).ToList();

            var list = repeat.FindAll(t => t.num > 1);

            list.ForEach(file =>
            {
                var files = TestListPair.FindAll(f => f.Key.Contains(file.name));
                //只保留第一个，其余的删除掉
                for (int i = 1; i < files.Count; i++)
                {
                    File.Delete(files[i].Value);
                }
            });

            MessageBox.Show("完成");
        }

        /// <summary>
        /// 获得指定路径下所有文件名
        /// </summary>
        /// <param name="sw">文件写入流</param>
        /// <param name="path">文件写入流</param>
        /// <param name="indent">输出时的缩进量</param>
        private void getFileName(string path)
        {
            DirectoryInfo root = new DirectoryInfo(path);
            var files = root.GetFiles();
            foreach (FileInfo f in files)
            {
                KeyValuePair<string, string> pair = new KeyValuePair<string, string>(f.Name, f.FullName);
                this.TestListPair.Add(pair);
            }
        }

        /// <summary>
        /// 获得指定路径下所有子目录名
        /// </summary>
        /// <param name="path">文件夹路径</param>
        private void getDirectory(string path)
        {
            getFileName(path);
            DirectoryInfo root = new DirectoryInfo(path);
            var directories = root.GetDirectories();
            foreach (DirectoryInfo d in directories)
            {
                getDirectory(d.FullName);
            }
        }

        private void btnTouchBtn_Click(object sender, EventArgs e)
        {
            FrmWinTouch frm = new FrmWinTouch();
            frm.Show();
        }

        private void btnXmlTest_Click(object sender, EventArgs e)
        {
            WaWi model = new WaWi();
            model.AMsg.RequesterNumber = "123456";
            model.AMsg.Records.Add(new Record { BarCode = "Barcode123" });
            string xmlStr = Utils.SerializeXml(model);

            string xmlPath = Application.StartupPath + "\\XML\\wawi.xml";
            var result = Utils.XmlDeserializeByFile<WaWi>(xmlPath);
            var msg = result.AMsg;

            xmlPath = Application.StartupPath + "\\XML\\beijing3.xml";
            var result2 = Utils.XmlDeserializeByFile<beijing3>(xmlPath);
            var msg2 = result2.operateinfo.info.method;

            result2 = Utils.XmlDeserialize<beijing3>(xml);
            result2 = null;
            result2 = Utils.XmlDeserialize2<beijing3>(xml);

            MedPresInfo medList = new MedPresInfo();
            medList.MedListModel.Add(new MedModel { MedCode = "100", MedName = "测试1" });
            medList.MedListModel.Add(new MedModel { MedCode = "200", MedName = "测试2" });
            xmlStr = Utils.SerializeXml(medList);
        }

        private void btnProcess_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("F:\\MyProjects\\G_IS.OD.HighSpeedDrugSystem\\02 Source Code\\Trunk\\G_IS.OD.DebugTools\\G_IS.OD.DebugTools.sln");
        }

        string xml = "<?xml version=\"1.0\" encoding=\"gb2312\"?>\n <root><commitdata><data><datarow/></data></commitdata> <returndata><data><datarow drug_code=\"82020201\" sub_code=\"\" drugname=\"头孢克洛胶囊\" specification=\"250mgx10粒/盒\" fy_unit=\"盒\" pack_unit=\"盒\" yp_ratio=\"\" py_code=\"TBKL\" manu_code=\"02078\" retprice=\"2.185000000000000e+001\" group_no=\"207500\"/> <datarow drug_code=\"80107900\" sub_code=\"\" drugname=\"罗氏芬(注射用头孢曲松钠)\" specification=\"1g/支\" fy_unit=\"支\" pack_unit=\"支\" yp_ratio=\"\" py_code=\"LSFZSYTB\" manu_code=\"23684\" retprice=\"4.938000000000000e+001\" sort_no=\"A010409 \" group_no=\"207500\"/><datarow drug_code=\"80021904\" sub_code=\"\" drugname=\"螺内酯片\" specification=\"20mg x20片/袋\" fy_unit=\"袋\" pack_unit=\"袋\" yp_ratio=\"\" py_code=\"LNZP\" manu_code=\"00105D\" retprice=\"3.300000000000000e+000\" group_no=\"207500\"/></data></returndata><operateinfo><info method=\"HIE_YTJ_yp_base\" opt_id=\"00000\" opt_name=\"00000\" opt_ip=\"80000001\" opt_date=\"2014 - 06 - 06\" guid=\"201506290000006\" token=\"AUTO - YYRMYY - 20140701\"/></operateinfo><result><info execute_flag=\"0\" execute_message=\"执行成功\" account=\"2021-09-17 11:53:40\"/></result></root>";

        private void btnTestCMD_Click(object sender, EventArgs e)
        {
            try
            {
                var ret = CMDTools.RunBatFile(txtCMDFile.Text.Trim(), false);

                DateTime timeStart = DateTime.Now;
                while (true)
                {
                    var procs = Process.GetProcessesByName("SAE_Control");
                    //执行时间
                    var span = (DateTime.Now - timeStart).Milliseconds;
                    if (procs.Length <= 0)
                    {
                        //超过5秒当作超时处理
                        if (span >= 5000)
                        {
                            MessageBox.Show("SAE Open Timeout!");
                            break;
                        }
                        Thread.Sleep(100);
                        continue;
                    }

                    foreach (var proc in procs)
                    {
                        var fileVersion = proc.MainModule.FileVersionInfo;
                        MessageBox.Show($"{fileVersion.FileDescription} {fileVersion.FileVersion}");
                    }
                    break;
                }

                //var ret = CMDTools.ShowRunCmdCommand(@"F:\Doc\药房项目\Riedl项目\Riedl程序\SAE_Control\SAE_Control.exe", "-Y_UNREVERSED -NEWG -IP192.168.81.112 -LOGLEVEL4 -CA_PORT51051 -ROBOT1 -LONG_TIMEOUTS -ACQUIRE");

                //var ss = CMDTools.HideRunCmdCommand(@"F:\Doc\药房项目\Riedl项目\Riedl程序\SAE_Control\SAE_Control.exe", "-Y_UNREVERSED -NEWG -IP192.168.81.112 -LOGLEVEL4 -CA_PORT51051 -ROBOT1 -LONG_TIMEOUTS -ACQUIRE");

                //CMDTools.HideAsyncRunCmdCommand(@"F:\Doc\药房项目\Riedl项目\Riedl程序\SAE_Control\SAE_Control.exe -Y_UNREVERSED -NEWG -IP192.168.81.112 -LOGLEVEL4 -CA_PORT51051 -ROBOT1 -LONG_TIMEOUTS -ACQUIRE");
                //var ii = CMDTools.GetAsyncRunCmdCommandInfo();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 录音 
        /// </summary>
        private void btnRecord_Click(object sender, EventArgs e)
        {
            if (btnRecord.Tag.ToString() == "1")
            {
                nar.SetFileName(@"d:\naudio.wav");
                nar.StartRec();
                btnRecord.Tag = "2";
                btnRecord.Text = "停止";
            }
            else
            {
                nar.StopRec();
                btnRecord.Tag = "1";
                btnRecord.Text = "录音";
            }
        }

        /// <summary>
        /// Excel导入 需安装Access Database Engine
        /// </summary>
        private void btnExcel_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            DialogResult result = openFileDialog1.ShowDialog();
            if (result != DialogResult.OK)
            {
                return;
            }
            string filePath = openFileDialog1.FileName;
            //读取
            var excelfile = new ExcelQueryFactory(filePath);
            //用另一种方法取得实体数据集
            var tsheet = excelfile.Worksheet<ImportReport>(0);
            var query = from p in tsheet
                        select p;
            var list = query.ToList();
            var model = list[0];
        }

        private void btnProvs_Click(object sender, EventArgs e)
        {
            CProvincialCapital proCap = new CProvincialCapital("南京市", 10000000);
            CProvince pro = new CProvince("江苏省", proCap, 8);
            List<CProvince> pros = new List<CProvince>();
            pros.Add(pro);

            proCap = new CProvincialCapital("杭州市", 20000000);
            pro = new CProvince("浙江省", proCap, 9);
            pros.Add(pro);

            CCountry cou = new CCountry("中国", pros, pro);

            pGrid.SelectedObject = cou;
        }

        private void btnDatabase_Click(object sender, EventArgs e)
        {
            Database database = new Database();
            pGrid.SelectedObject = database;
        }

        private void btnProperty_Click(object sender, EventArgs e)
        {
            var obj = pGrid.SelectedObject;
        }
    }
}
